﻿using System.Net.Http;
using System.Net.Http.Headers;
using Flurl;
using ZilLion.Core.ConfigManager.Manager;
using ZilLion.Core.Unities.UnitiesMethods;
using ZilLion.TPO2O.SDK.EntityBase;

namespace ZilLion.TPO2O.SDK.Request
{
    public class DefaultRequester : IO2ORequester
    {
        public const string DefaultBodyKey = "defualtrequestbody";


        /// <summary>
        ///     目标平台
        /// </summary>
        private readonly TokenRequestConfig _tokenRequestConfig;

        public DefaultRequester(string tpapptype, string zlusercode, string zlapptype, string zlauthkey)
        {
            _tokenRequestConfig = new TokenRequestConfig
            {
                ZlAppType = zlapptype,
                ZlAuthkey = zlauthkey,
                TpApptype = tpapptype,
                ZlUserCode = zlusercode
            };
        }

        public DefaultRequester(TokenRequestConfig tokenRequestConfig)
        {
            _tokenRequestConfig = tokenRequestConfig;
        }

        /// <summary>
        ///     业务请求
        /// </summary>
        /// <param name="requestBusinessKey"></param>
        /// <param name="requestParams"></param>
        /// <returns></returns>
        public virtual O2OResponseResultInfo BusinessRequest(string requestBusinessKey,
            RequestParamsWrapper requestParams = null)
        {
            O2OResponseResultInfo result = null;

            #region 处理url

            var requesturl = Url.Combine(CreateRequestUrl(), requestBusinessKey);
            var token = GetToken();
            requesturl = requesturl + $"?token={token}";

            #endregion

            if (requestParams != null)
                result = HttpHelper.HttpRequestPost<O2OResponseResultInfo>(requesturl,
                    new StringContent(requestParams.CreateRequest())
                    {
                        Headers = {ContentType = new MediaTypeHeaderValue("application/json")}
                    });


            return result;
        }


        protected virtual string CreateRequestUrl()
        {
            var host = ZilLionConfigurationManager.GetConfigInstance<Tpo2OSdkConfig>().ProxyHost;
            return Url.Combine(host, "Api", _tokenRequestConfig.TpApptype);
        }


        public virtual string GetToken()
        {
            return TokenContainer.Instance().TryGetToken(_tokenRequestConfig);
        }
    }
}